from flask import Blueprint, request, render_template, redirect, url_for, flash, session
from applications.models.frontend import Address, User
from applications.extensions import db
from functools import wraps

from applications.view.user.decorators import login_required # 从新的模块导入装饰器
# 创建地址管理蓝图
address_bp = Blueprint('address', __name__)


# 前台地址管理
@address_bp.route('/address_management')
@login_required
def address_management():
    user_id = session.get('user_id')
    user = User.query.get(user_id) if user_id else None
    return render_template('user/address/address_management.html', user=user)

# 前台添加地址
@address_bp.route('/add_address', methods=['GET', 'POST'])
@login_required
def add_address():
    if request.method == 'POST':
        user_id = session.get('user_id')
        recipient_name = request.form.get('recipient_name')
        phone = request.form.get('phone')
        address_line = request.form.get('address_line')
        is_default = request.form.get('is_default') == 'on'

        new_address = Address(user_id=user_id, recipient_name=recipient_name, phone=phone, address_line=address_line, is_default=is_default)
        db.session.add(new_address)
        db.session.commit()
        flash('地址添加成功！', 'success')
        return redirect(url_for('address.address_management'))

    return render_template('user/address/add_address.html')

# 前台编辑地址
@address_bp.route('/edit_address/<int:address_id>', methods=['GET', 'POST'])
@login_required
def edit_address(address_id):
    address = Address.query.get(address_id)
    if request.method == 'POST':
        if address:
            address.recipient_name = request.form.get('recipient_name')
            address.phone = request.form.get('phone')
            address.address_line = request.form.get('address_line')
            address.is_default = request.form.get('is_default') == 'on'
            db.session.commit()
            flash('地址更新成功！', 'success')
        else:
            flash('地址不存在！', 'danger')
        return redirect(url_for('address.address_management'))

    return render_template('user/address/edit_address.html', address=address)

# 前台删除地址
@address_bp.route('/delete_address/<int:address_id>')
@login_required
def delete_address(address_id):
    address = Address.query.get(address_id)
    if address:
        db.session.delete(address)
        db.session.commit()
        flash('地址删除成功！', 'danger')
    else:
        flash('地址不存在！', 'danger')
    return redirect(url_for('address.address_management'))

# 注册地址管理蓝图
def register_address_bps(app):
    app.register_blueprint(address_bp, url_prefix='/address')